<?php

namespace App\Observers;

use App\Helpers\KeyHandler;
use App\Models\Customer;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;

class CustomerObserver
{
    public function saved(Customer $customer)
    {
        $this->clearCache($customer);
    }

    public function deleted(Customer $customer)
    {
        $this->clearCache($customer);
    }


    private function clearCache(Customer $customer)
    {
        //删除统计缓存
        if ($customer->sale_time) {
            $customer->sale_time = Carbon::parse($customer->sale_time);
            $year = $customer->sale_time->year;
            $month = str_pad($customer->sale_time->month, 2, 0, STR_PAD_LEFT);
            Cache::forget(sprintf(KeyHandler::SALE_STATISTICS, 'day', $year . '-' . $month));
            Cache::forget(sprintf(KeyHandler::SALE_STATISTICS, 'month', $year . '-' . $month));
        }

        if ($customer->time_of_appointment) {
            $customer->time_of_appointment = Carbon::parse($customer->time_of_appointment);
            $year = $customer->time_of_appointment->year;
            $month = str_pad($customer->time_of_appointment->month, 2, 0, STR_PAD_LEFT);
            Cache::forget(sprintf(KeyHandler::SALE_STATISTICS, 'day', $year . '-' . $month));
            Cache::forget(sprintf(KeyHandler::SALE_STATISTICS, 'month', $year . '-' . $month));
        }

        if ($customer->consultation) {
            $customer->consultation = Carbon::parse($customer->consultation);
            $year = $customer->consultation->year;
            $month = str_pad($customer->consultation->month, 2, 0, STR_PAD_LEFT);
            Cache::forget(sprintf(KeyHandler::SALE_STATISTICS, 'day', $year . '-' . $month));
            Cache::forget(sprintf(KeyHandler::SALE_STATISTICS, 'month', $year . '-' . $month));
        }


        if ($customer->deal) {
            $customer->deal = Carbon::parse($customer->deal);
            $year = $customer->deal->year;
            $month = str_pad($customer->deal->month, 2, 0, STR_PAD_LEFT);
            Cache::forget(sprintf(KeyHandler::SALE_STATISTICS, 'day', $year . '-' . $month));
            Cache::forget(sprintf(KeyHandler::SALE_STATISTICS, 'month', $year . '-' . $month));
        }

    }
}
